//
// Created by spiro on 19-3-25.
//

#include <stdio.h>
#include <stdlib.h>
#include "list.h"

void showmovies(Item item);
char * s_gets(char * st, int n);

int main(void) {
    List movies;
    Item temp;

    InitializeList(&movies);

    while (1) {
        if (ListIsFull(&movies)) {
            puts("The list is now full.");
            break;
        }

        puts("Please enter movie title:");

        if (s_gets(temp.title, TSIZE) == NULL || temp.title[0] == '\0') {
            break;
        }

        puts("Please enter rating <0-10>:");
        scanf("%d", &temp.rating);
        while (getchar() != '\n')
            continue;

        if (!AddItem(temp, &movies)) {
            fprintf(stderr, "Add item failed.");
            break;
        }
    }

    // show
    if (ListIsEmpty(&movies)) {
        puts("No data.");
    } else {
        puts("Movie list:");
        Traverse(&movies, showmovies);
    }

    printf("Movie count: %d\n", ListItemCount(&movies));

    EmptyTheList(&movies);
    printf("Bye!\n");

    return 0;
}

void showmovies(Item item) {
    printf("Movie: %s Rating: %d\n", item.title, item.rating);
}

char * s_gets(char * st, int n) {
    char * ret_val;
    int i = 0;

    ret_val = fgets(st, n, stdin);
    if (ret_val) {
        while (st[i] != '\n' && st[i] != '\0') {
            i++;
        }

        if (st[i] == '\n') {
            st[i] = '\0';
        } else {
            while (getchar() != '\n') {
                continue;
            }
        }
    }
    return ret_val;
}